import type { Component } from 'vue';
import { ref, reactive } from 'vue';

interface DialogOptions {
  title: string;
  component: string | Component;
  componentProps?: Record<string, any>;
}

const globalDialogState = reactive({
  isOpen: false,
  title: '',
  component: null as string | Component | null,
  componentProps: {} as Record<string, any>,
  resolve: null as ((value: any) => void) | null,
});

export function useDynamicDialog() {
  async function openDialog<T = any>(options: DialogOptions): Promise<T | null> {
    globalDialogState.title = options.title;
    globalDialogState.component = options.component;
    globalDialogState.componentProps = options.componentProps || {};
    globalDialogState.isOpen = true;

    return new Promise<T | null>((resolve) => {
      globalDialogState.resolve = resolve;
    });
  }

  function closeDialog(result?: any) {
    globalDialogState.isOpen = false;
    if (globalDialogState.resolve) {
      globalDialogState.resolve(result);
      globalDialogState.resolve = null;
    }
  }

  function cancelDialog() {
    closeDialog(null);
  }

  return {
    dialogState: globalDialogState,
    openDialog,
    closeDialog,
    cancelDialog,
  };
}